import com.fakepackage.PersistenceMgr
import com.fakepackage.Triathlon
import java.text.SimpleDateFormat

def triname = request.getParameter("tri_name")
def tridesc = request.getParameter("tri_description")
def month = request.getParameter("tri_month")
def day = request.getParameter("tri_day")
def year = request.getParameter("tri_year")
def message = ""
def triathlons // = new ArrayList<Triathlon>()
def mgr

// Create new
if(triname!=null){
def formatter = new SimpleDateFormat("MM/dd/yyyy")
def tridate = formatter.parse("${month}/${day}/${year}")

def triathlon = new Triathlon(tridate, triname, tridesc)

try {
mgr = PersistenceMgr.manufacture()
mgr.makePersistent(triathlon)
message += "Successfully saved: ${triathlon}.\n"
} catch(ex) {
message += "Exception caught when creating record: ${ex}.\n"
} finally {
mgr.close()
}
}

// Get existing records
try {
mgr = PersistenceMgr.manufacture()
def query = "select from com.fakepackage.Triathlon"
triathlons = (List<Triathlon>) mgr.newQuery(query).execute();
mgr.detachCopyAll(triathlons);
} catch(ex) { 
message += "Exception caught when reading records: ${ex}."
} finally {
mgr.close()
}

html.html { // html is implicitly bound to new MarkupBuilder(out)
head {
title("Triathlons")
}
body {
form(action:"triathlon.groovy"){
label(for:"tri_name", "Name:")
input(type:"text", name:"tri_name", id: "tri_name", value:"sample triathlon")
br()
label(for:"tri_description", "Description:")
input(type:"text", name:"tri_description", id: "tri_description", value:"sample desc")
br()
label(for:"tri_month", "Month:")
input(type:"text", name:"tri_month", id: "tri_month", value:"6")
br()
label(for:"tri_day", "Day:")
input(type:"text", name:"tri_day", id: "tri_day", value:"1")
br()
label(for:"tri_year", "Year:")
input(type:"text", name:"tri_year", id: "tri_year", value:"2010")
br()
input(type:"submit", value:"Save")
br()
}

p(message)

if(triathlons.size()>0){
table(cellpadding:"5", cellspacing:"0", border:"1"){
tr{
th("Name")
th("Description")
th("Date")
}
triathlons.each{ record ->
tr{
td(record.name)
td(record.description)
td(record.date)
}
}
}
}
}
}